import Taro, { Component } from '@tarojs/taro'
import { View, Button, Text, Block, Image, Navigator } from '@tarojs/components'

import allRequest from './../../api/allRequest'
import allExtrance from './../../config/allExtrance'
import './jobList.less'

class JobList extends Component {
    static externalClasses = ['my-class']

    constructor(props) {
        super(props)
        this.state = {
            salary_unit: ['', '元/月', '元/日', '元/时'],
            savePosterShow: false,
            posterTempFilePath: '',
            educationArr: ['学历不限', '小学', '初中', '中专', '高中', '大学专科', '大学本科', '硕士', '博士', '博士后', '其它'],
            tagArr: []
        }
    }

    componentWillReceiveProps(nextProps) {
        console.log(this.props, nextProps)
    }

    componentDidMount() {
        if (!Taro.getStorageSync('tag')) {
            allRequest.tag()
                .then(res => {
                    let { tagArr } = this.state
                    for (let i in res) {
                        if (i != '__info') {
                            tagArr.push(res[i])
                        }
                    }
                    allExtrance.util.Taro.setStorageSync('tag', tagArr)
                    this.setState({ tagArr })
                })
                .catch(err => console.log(err))
        } else {
            this.setState({
                tagArr: JSON.parse(Taro.getStorageSync('tag'))
            })
        }
    }

    componentWillUnmount() {
        Taro.getSetting({
            success: res => {
                this.authSetting = res.authSetting
            }
        })
    }

    componentDidShow() { }

    componentDidHide() { }

    transDate(str) {
        if (typeof str != 'undefined') {
            str = str.split('-');
            str[2] = str[2].split(' ')
            return str[1] + '月' + str[2][0] + '日';
        }
    }

    switchToJobInfo(job_id, e) {
        e.stopPropagation();
        Taro.navigateTo({
            url: `/subPackages/subPackageS/jobInfo/jobInfo?companyJobId=${job_id}&fromId=`
        })
    }

    //需求：点击当前按钮，显示海报生成窗口
    //点击保存，获取权限后，保存到本地
    getPoster(companyjobid, e) {
        e.stopPropagation();
        this.setState({
            savePosterShow: true
        })
        Taro.showLoading({
            title: '生成中...'
        })
        //海报生成
        allRequest.JobPoster({ "jobId": companyjobid }).then((result) => {
            Taro.hideLoading()
            if (result.status) {
                this.setState({
                    posterTempFilePath: result.data,
                    savePosterShow: true
                })
            } else {
                Taro.showToast({
                    icon: 'none',
                    title: '网络不稳定，请重新生成'
                })
            }
        }).catch((err) => {
            Taro.hideLoading()
            Taro.showToast({
                icon: 'none',
                title: '网络不稳定，请重新生成'
            })
        });
    }

    savePoster(e) {
        e.stopPropagation()
        Taro.showLoading({
            title: '保存中...'
        })
        let { posterTempFilePath } = this.state
        let promise = new Promise((resolve,reject)=>{
            try {
                Taro.downloadFile({
                    url: posterTempFilePath,
                    header: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                }).then((data)=>{
                    Taro.getSetting().then((res) => {
                        if (res.authSetting['scope.writePhotosAlbum'] != undefined && res.authSetting['scope.writePhotosAlbum'] != true) {//非初始化进入该页面,且未授权
                            Taro.hideLoading()
                            Taro.showModal({
                                title: '是否授权允许访问相册',
                                content: '需要访问您的相册，否则无法保存海报',
                                success:(result)=>{
                                    if(result.confirm){
                                        Taro.openSetting().then((datal) => {
                                            if (datal.authSetting["scope.writePhotosAlbum"] == true) {
                                                allExtrance.util.Taro.showToast('授权成功')
                                                Taro.saveImageToPhotosAlbum({
                                                    filePath: data.tempFilePath
                                                }).then(() => {
                                                    resolve('success')
                                                }).catch(err => {
                                                    reject(err.errMsg)
                                                })
                                            } else {
                                                reject('您已拒绝授权')
                                            }
                                        }).catch(err =>{reject(err.errMsg)})
                                    }else if (result.cancel){
                                        reject('您已拒绝授权')
                                    }
                                }
                            })
                        } else if (res.authSetting['scope.writePhotosAlbum'] == true || typeof res.authSetting['scope.writePhotosAlbum'] == 'undefined') {
                            Taro.authorize({
                                scope: 'scope.writePhotosAlbum',
                            }).then(() => {
                                return Taro.saveImageToPhotosAlbum({
                                    filePath: data.tempFilePath
                                }).then(() => {
                                    resolve('success')
                                }).catch(err => {
                                    reject(err.errMsg)
                                })
                            }).catch(err => {
                                reject('您已拒绝授权')
                            })
                        }
                    }).catch(err =>{reject(err.errMsg)})
                }) 
            } catch (error) {
                reject(error)
            }
        })

        promise.then(result =>{
            if(result =='success'){
                Taro.hideLoading()
                Taro.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                })
                this.setState({ savePosterShow: false })
            }
        }).catch(err =>{
            Taro.hideLoading()
            Taro.showToast({
                title: `保存失败：原因${err}`,
                icon: 'none',
                duration: 2000
            })
        })
    }

    hideSavePoster() {
        this.setState({
            savePosterShow: false
        })
    }

    noop(e) {
        e.stopPropagation();
        return false
    }

    render() {
        let { jobs, companyStatus } = this.props
        let { salary_unit, educationArr, tagArr } = this.state
        return (
            <View className='jobList'>
                <View className='job-list my-class'>
                    {
                        jobs && jobs.length > 0 && jobs.map((item, index) =>
                            <Block>
                                <View className={`job-cell ${companyStatus == 2 && 'disable'}`}>
                                    {
                                        companyStatus == 1 && <View className='row row-0 dis-flex flex-between flex-middle'>
                                            <View className='post-time'>{item.pv + item.avatar_pv}人查看</View>
                                            <View className='row_g dis-flex flex-center flex-nowrap'>
                                                {
                                                    item.review_status == 1 ? <Block>
                                                        <View className='row_g_switchToJobInfo' onClick={this.switchToJobInfo.bind(this, item.job_id)}>查看岗位</View>
                                                        <View className='row_g_getPoster' onClick={this.getPoster.bind(this, item.job_id)}>生成海报</View>
                                                    </Block> : <Block>
                                                            <View className='row_g_inReview'>审核中</View>
                                                        </Block>
                                                }
                                            </View>
                                        </View>
                                    }

                                    <Navigator className='content' url={`/subPackages/subPackageF/publicJob/publicJob?companyJobId=${item.job_id}&companyStatus=${companyStatus}`} hover-className='none' >
                                        <View className='row row-1'>
                                            <View className='position-name'>{item.job_title || item.position.position_title}</View>
                                            {
                                                item.salary_unit != 4 ? <View className='salary'>
                                                    {
                                                        item.salary_max == item.salary_min ? <Text className='num'>{item.salary_max}</Text> : <Text className='num'>{item.salary_min}-{item.salary_max}</Text>
                                                    }
                                                    <Text className='unit'> {salary_unit[item.salary_unit]}</Text>
                                                </View> :
                                                    <View className='salary'>
                                                        <Text className='num'>面议</Text>
                                                    </View>
                                            }
                                        </View>
                                        {
                                            item.company && <View className='row row-2'>
                                                <View className='poi-name'>{item.company.title || '未知企业'}</View>
                                                {(!item.tag || item.tag.length === 0) && <View className='distance-str'>{item.distanceStr}</View>}
                                            </View>
                                        }

                                        <View className='row row-3'>
                                            <View className='condition'>
                                                <View className='item'>{educationArr[item.job_education]}</View>
                                                {item.job_experience_min == item.job_experience_max && item.job_experience_max == 0 && <View className='item'>经验不限</View>}
                                                {item.job_experience_min == item.job_experience_max && item.job_experience_max != 0 && <View className='item'>{item.job_experience_max + '年'}</View>}
                                                {item.job_experience_min != item.job_experience_max && <View className='item'>{item.job_experience_min + '-' + item.job_experience_max}年</View>}
                                            </View>
                                            {
                                                item.tag.length === 0 && <Block>
                                                    <View className='public-time'>{this.transDate(item.time_update)}</View>
                                                </Block>
                                            }
                                        </View>
                                        {
                                            (item.tag && item.tag.length > 0) && <View className='row row-4'>
                                                <View className='welfares'>
                                                    {
                                                        item.tag.map((tag, index) => <Block>
                                                            {index < 4 && <View className='item' style={`color:${Taro.getStorageSync('welfareColor')};border:1px solid ${Taro.getStorageSync('welfareColor')}`}>{tagArr[Number(tag.tag_type) - 1]}</View>}
                                                        </Block>)
                                                    }
                                                </View>
                                                <View className='public-time'>{this.transDate(item.time_update)}</View>
                                            </View>
                                        }

                                    </Navigator>
                                </View>
                            </Block>
                        )
                    }

                </View>
                {
                    this.state.savePosterShow && <Block>
                        <View className='save-poster' onClick={this.hideSavePoster} catchtouchmove='noop'>
                            <View className='content' onClick={this.noop.bind(this)}>
                                <Image className='image' src={this.state.posterTempFilePath} />
                                <Button className='button' onClick={this.savePoster.bind(this)} style={`background:${Taro.getStorageSync('baseColor')}`}>{Taro.getEnv() === Taro.ENV_TYPE.WEB?'长按保存海报':'保存海报'}</Button>
                            </View>
                        </View>
                    </Block>
                }

            </View>
        )
    }
}

JobList.defaultProps = {
    jobs: [],
    companyStatus: 1
}

export default JobList
